import { useCallback, useRef, useState, useEffect } from 'react';

interface UseResizableProps {
  enabled: boolean;
  minWidth?: number;
  minHeight?: number;
  maxWidth?: number;
  maxHeight?: number;
  onResize?: (width: number, height: number) => void;
  onResizeStart?: () => void;
  onResizeEnd?: () => void;
}

interface ResizeState {
  width: number;
  height: number;
  isResizing: boolean;
}

export const useResizable = ({
  enabled,
  minWidth = 200,
  minHeight = 150,
  maxWidth,
  maxHeight,
  onResize,
  onResizeStart,
  onResizeEnd,
}: UseResizableProps) => {
  const [resizeState, setResizeState] = useState<ResizeState>({
    width: 0,
    height: 0,
    isResizing: false,
  });

  const startPositionRef = useRef({ x: 0, y: 0 });
  const startSizeRef = useRef({ width: 0, height: 0 });
  const isResizingRef = useRef(false);

  // 处理鼠标按下事件
  const handleMouseDown = useCallback(
    (event: React.MouseEvent) => {
      if (!enabled) return;

      event.preventDefault();
      event.stopPropagation();

      const target = event.currentTarget.closest('.modal-sheet') as HTMLElement;
      if (!target) return;

      const rect = target.getBoundingClientRect();
      
      startPositionRef.current = {
        x: event.clientX,
        y: event.clientY,
      };
      
      startSizeRef.current = {
        width: rect.width,
        height: rect.height,
      };

      isResizingRef.current = true;
      setResizeState(prev => ({ ...prev, isResizing: true }));
      
      onResizeStart?.();

      // 添加全局事件监听器
      document.addEventListener('mousemove', handleMouseMove);
      document.addEventListener('mouseup', handleMouseUp);
    },
    [enabled, onResizeStart]
  );

  // 处理触摸开始事件
  const handleTouchStart = useCallback(
    (event: React.TouchEvent) => {
      if (!enabled) return;

      event.preventDefault();
      event.stopPropagation();

      const target = event.currentTarget.closest('.modal-sheet') as HTMLElement;
      if (!target) return;

      const rect = target.getBoundingClientRect();
      const touch = event.touches[0];
      
      startPositionRef.current = {
        x: touch.clientX,
        y: touch.clientY,
      };
      
      startSizeRef.current = {
        width: rect.width,
        height: rect.height,
      };

      isResizingRef.current = true;
      setResizeState(prev => ({ ...prev, isResizing: true }));
      
      onResizeStart?.();

      // 添加全局事件监听器
      document.addEventListener('touchmove', handleTouchMove);
      document.addEventListener('touchend', handleTouchEnd);
    },
    [enabled, onResizeStart]
  );

  // 处理鼠标移动
  const handleMouseMove = useCallback((event: MouseEvent) => {
    if (!isResizingRef.current) return;

    const deltaX = event.clientX - startPositionRef.current.x;
    const deltaY = event.clientY - startPositionRef.current.y;

    const newWidth = Math.max(
      minWidth,
      Math.min(
        maxWidth || window.innerWidth,
        startSizeRef.current.width + deltaX
      )
    );

    const newHeight = Math.max(
      minHeight,
      Math.min(
        maxHeight || window.innerHeight,
        startSizeRef.current.height + deltaY
      )
    );

    setResizeState(prev => ({
      ...prev,
      width: newWidth,
      height: newHeight,
    }));

    onResize?.(newWidth, newHeight);
  }, [minWidth, minHeight, maxWidth, maxHeight, onResize]);

  // 处理触摸移动
  const handleTouchMove = useCallback((event: TouchEvent) => {
    if (!isResizingRef.current) return;

    const touch = event.touches[0];
    const deltaX = touch.clientX - startPositionRef.current.x;
    const deltaY = touch.clientY - startPositionRef.current.y;

    const newWidth = Math.max(
      minWidth,
      Math.min(
        maxWidth || window.innerWidth,
        startSizeRef.current.width + deltaX
      )
    );

    const newHeight = Math.max(
      minHeight,
      Math.min(
        maxHeight || window.innerHeight,
        startSizeRef.current.height + deltaY
      )
    );

    setResizeState(prev => ({
      ...prev,
      width: newWidth,
      height: newHeight,
    }));

    onResize?.(newWidth, newHeight);
  }, [minWidth, minHeight, maxWidth, maxHeight, onResize]);

  // 处理鼠标释放
  const handleMouseUp = useCallback(() => {
    if (!isResizingRef.current) return;

    isResizingRef.current = false;
    setResizeState(prev => ({ ...prev, isResizing: false }));
    
    onResizeEnd?.();

    // 移除全局事件监听器
    document.removeEventListener('mousemove', handleMouseMove);
    document.removeEventListener('mouseup', handleMouseUp);
  }, [onResizeEnd, handleMouseMove]);

  // 处理触摸结束
  const handleTouchEnd = useCallback(() => {
    if (!isResizingRef.current) return;

    isResizingRef.current = false;
    setResizeState(prev => ({ ...prev, isResizing: false }));
    
    onResizeEnd?.();

    // 移除全局事件监听器
    document.removeEventListener('touchmove', handleTouchMove);
    document.removeEventListener('touchend', handleTouchEnd);
  }, [onResizeEnd, handleTouchMove]);

  // 清理事件监听器
  useEffect(() => {
    return () => {
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
      document.removeEventListener('touchmove', handleTouchMove);
      document.removeEventListener('touchend', handleTouchEnd);
    };
  }, [handleMouseMove, handleMouseUp, handleTouchMove, handleTouchEnd]);

  // 重置大小状态
  const resetSize = useCallback(() => {
    setResizeState({
      width: 0,
      height: 0,
      isResizing: false,
    });
  }, []);

  return {
    resizeState,
    handleMouseDown,
    handleTouchStart,
    resetSize,
    resizeStyles: resizeState.width > 0 && resizeState.height > 0 ? {
      width: `${resizeState.width}px`,
      height: `${resizeState.height}px`,
    } : {},
  };
};
